<template>
  <div class="history-container">
    <h2>识别历史记录</h2>
    
    <!-- 筛选器 -->
    <div class="filters">
      <div class="search-box">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索标签或类别..."
          @input="filterRecords"
        >
      </div>
      <div class="date-filter">
        <input 
          type="date" 
          v-model="startDate"
          @change="filterRecords"
        >
        <span>至</span>
        <input 
          type="date" 
          v-model="endDate"
          @change="filterRecords"
        >
      </div>
    </div>

    <!-- 历史记录列表 -->
    <div class="history-list">
      <div v-if="loading" class="loading">
        加载中...
      </div>
      <div v-else-if="filteredRecords.length === 0" class="no-records">
        暂无历史记录
      </div>
      <div v-else class="records">
        <div v-for="record in filteredRecords" :key="record.id" class="record-card">
          <div class="record-image">
            <img :src="record.image_url" :alt="record.label">
          </div>
          <div class="record-info">
            <h3>{{ record.label }}</h3>
            <p>类别 ID：{{ record.class_id }}</p>
            <p>置信度：{{ (record.confidence * 100).toFixed(2) }}%</p>
            <p>识别时间：{{ formatDate(record.created_at) }}</p>
          </div>
          <div class="record-actions">
            <button @click="deleteRecord(record)" class="delete-btn">
              删除
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <button 
        :disabled="currentPage === 1"
        @click="changePage(currentPage - 1)"
      >
        上一页
      </button>
      <span>第 {{ currentPage }} 页，共 {{ totalPages }} 页</span>
      <button 
        :disabled="currentPage === totalPages"
        @click="changePage(currentPage + 1)"
      >
        下一页
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

const records = ref([])
const loading = ref(false)
const searchQuery = ref('')
const startDate = ref('')
const endDate = ref('')
const currentPage = ref(1)
const pageSize = 10

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取历史记录
const fetchRecords = async () => {
  loading.value = true
  try {
    const response = await fetch('/api/history', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    if (!response.ok) throw new Error('获取历史记录失败')
    records.value = await response.json()
  } catch (error) {
    console.error('Error fetching records:', error)
  } finally {
    loading.value = false
  }
}

// 过滤记录
const filteredRecords = computed(() => {
  let filtered = [...records.value]
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(record => 
      record.label.toLowerCase().includes(query) ||
      record.class_id.toString().includes(query)
    )
  }
  
  // 日期过滤
  if (startDate.value) {
    filtered = filtered.filter(record => 
      new Date(record.created_at) >= new Date(startDate.value)
    )
  }
  if (endDate.value) {
    filtered = filtered.filter(record => 
      new Date(record.created_at) <= new Date(endDate.value)
    )
  }
  
  return filtered
})

// 分页
const totalPages = computed(() => 
  Math.ceil(filteredRecords.value.length / pageSize)
)

const paginatedRecords = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  const end = start + pageSize
  return filteredRecords.value.slice(start, end)
})

const changePage = (page) => {
  currentPage.value = page
}

// 删除记录
const deleteRecord = async (record) => {
  if (!confirm('确定要删除这条记录吗？')) return
  
  try {
    const response = await fetch(`/api/history/${record.id}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    if (!response.ok) throw new Error('删除记录失败')
    records.value = records.value.filter(r => r.id !== record.id)
  } catch (error) {
    console.error('Error deleting record:', error)
  }
}

onMounted(fetchRecords)
</script>

<style scoped>
.history-container {
  padding: 2rem;
  max-width: 1200px;
  margin: 0 auto;
}

h2 {
  color: #2c3e50;
  margin-bottom: 2rem;
}

.filters {
  display: flex;
  gap: 1rem;
  margin-bottom: 2rem;
}

.search-box {
  flex: 1;
}

.search-box input {
  width: 100%;
  padding: 0.8rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

.date-filter {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.date-filter input {
  padding: 0.8rem;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.records {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 1.5rem;
}

.record-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.record-image {
  width: 100%;
  height: 200px;
  overflow: hidden;
}

.record-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.record-info {
  padding: 1rem;
}

.record-info h3 {
  margin: 0 0 0.5rem 0;
  color: #2c3e50;
}

.record-info p {
  margin: 0.25rem 0;
  color: #666;
}

.record-actions {
  padding: 1rem;
  border-top: 1px solid #eee;
  text-align: right;
}

.delete-btn {
  padding: 0.5rem 1rem;
  background-color: #dc3545;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.delete-btn:hover {
  opacity: 0.9;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1rem;
  margin-top: 2rem;
}

.pagination button {
  padding: 0.5rem 1rem;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.pagination button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.loading, .no-records {
  text-align: center;
  padding: 2rem;
  color: #666;
}
</style> 